
#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;

- (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) launchOptions
{      
    mainView = [[MainView alloc] initWithFrame: [UIScreen mainScreen].applicationFrame]; 
    mainView.backgroundColor = [UIColor yellowColor];
    gcHelper = [[GCHelper alloc] init];
    gcHelper.view = mainView;  
    self.window = [[[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]] autorelease];
    self.window.rootViewController = gcHelper;     
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void) startGameLoop {    
    NSString *deviceOS = [[UIDevice currentDevice] systemVersion];    
    bool forceTimerVariant = TRUE;
    
    if (forceTimerVariant || [deviceOS compare: @"3.1" options: NSNumericSearch] == NSOrderedAscending) {
        //33 frames per second -> timestep between the frames = 1/33    
        NSTimeInterval fpsDelta = 0.0303;
        timer = [NSTimer scheduledTimerWithTimeInterval: fpsDelta
                                                 target: self
                                               selector: @selector( loop )
                                               userInfo: nil
                                                repeats: YES]; 
        
    } else {
        int frameLink = 2;
        timer = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget: self selector: @selector( loop )];
        [timer setFrameInterval: frameLink];
        [timer addToRunLoop: [NSRunLoop currentRunLoop] forMode: NSDefaultRunLoopMode];
    }
    
    NSLog(@"Game Loop timer instance: %@", timer);   
}

- (void) stopGameLoop {
    [timer invalidate];
    timer = nil;
}

- (void) loop {
	[mainView setNeedsDisplay]; //triggers MainView's drawRect:-method	
}

- (void) applicationDidBecomeActive: (UIApplication *) application {
    [self startGameLoop];
}

- (void) applicationWillResignActive: (UIApplication *) application {
    [self stopGameLoop];
}

- (void) applicationDidEnterBackground:  (UIApplication *) application {}
- (void) applicationWillEnterForeground:(UIApplication *) application {}
- (void) applicationWillTerminate: (UIApplication *) application {}

- (void) dealloc {
    [self stopGameLoop];
    [timer release];
    [_window release];
    [mainView release];
    [super dealloc];
}

@end
